package com.hzz.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author wujunjie
 * @date 2021/5/31 9:24
 * @desc 用于重构request body内容
 */
@Slf4j
public class RequestBodyServletRequestWrapper extends HttpServletRequestWrapper {

    private String body;

    public RequestBodyServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }
    public RequestBodyServletRequestWrapper(HttpServletRequest request, String bodyStr) {
        super(request);
        this.body=bodyStr;
    }
    /**
     * 重写getInputStream方法
     */
    @Override
    public ServletInputStream getInputStream() throws IOException {
        //重新构造一个输入流对象
        byte[] bytes =body.getBytes("utf-8");
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        return new BodyServletInputStream(bis);
    }
    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }
}
